import { state } from "../config.js";
import { currentRole, role, role1, role2 } from "../index.js";
import { allRolePosition } from "../role.js";
import { emit, on, scoket } from "../utils/scoket.js";
import { removeKey, setKey } from "./scheduler.js";

export const getPosition = (ele: HTMLElement) => {
  const po = ele.style.transform;
  const xy = po.slice(po.indexOf("(") + 1, po.indexOf(")")).split(",");
  return {
    x: +xy[0].replace("px", ""),
    y: +xy[1].replace("px", ""),
  };
};
//按键触发移动
let keyword = ["a", "s", "d", "w", "j"];
let lastKey = "";
export function transfrom(e: KeyboardEvent) {
  //如果当前状态是暂停则不进行下一步操作
  if (state.stop) return;
  if (!keyword.includes(e.key)) return;
  if (lastKey === e.key) return;
  lastKey = e.key;
  setKey(e.key);
}

scoket.$on((res) => {
  if (res.path !== "/key/down") return;
  if (res.role === "p1") {
    role1.style.transform = setTransfrom(res.value.rolePosition);
    allRolePosition.p1 = res.value.rolePosition;
  }
  if (res.role === "p2") {
    role2.style.transform = setTransfrom(res.value.rolePosition);
    allRolePosition.p2 = res.value.rolePosition;
  }
});

//停止移动
export function stopTransform(e: KeyboardEvent) {
  if (!keyword.includes(e.key)) return;
  lastKey = "";
  removeKey(e.key);
}

export const getRolePosition = () => {
  return getPosition(currentRole);
};

export const setTransfrom = (po: { x: number; y: number }) => {
  return `translate(${po.x}px, ${po.y}px)`;
};

export const setPosition = (ele: HTMLElement, po: { x: number; y: number }) => {
  ele.style.transform = setTransfrom(po);
};
